<template>
  <div class="profile-page">
    <el-row :gutter="24" align="stretch">
      <!-- 左：基本信息 -->
      <el-col :span="16">
        <el-card class="card-pro" shadow="never">
          <div class="card-header">
            <div class="title">个人资料</div>
            <div class="sub">管理您的基本信息</div>
          </div>

          <el-divider></el-divider>

          <el-form :model="userInfoForm" label-width="100px" class="pro-form">
            <el-form-item label="用户名">
              <el-input v-model="userInfoForm.name" disabled />
            </el-form-item>

            <el-form-item label="昵称">
              <el-input v-model="userInfoForm.nickname" placeholder="请输入昵称" />
            </el-form-item>

            <el-form-item label="邮箱">
              <el-input v-model="userInfoForm.email" placeholder="请输入邮箱" />
            </el-form-item>

            <el-form-item label="角色">
              <el-input v-model="userInfoForm.role" disabled />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveProfile">保存资料</el-button>
            </el-form-item>
          </el-form>

        </el-card>
      </el-col>

      <!-- 右：头像卡片 -->
      <el-col :span="8">
        <el-card class="card-pro avatar-card" shadow="never">
          <div class="avatar-area">
            <el-avatar :size="140" :src="userInfo.avatar" class="big-avatar" />
            <div class="avatar-name">{{ userInfo.username }}</div>
            <div class="avatar-role">{{ userInfo.role }}</div>
          </div>

          <el-divider></el-divider>

          <div class="upload-area">
            <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
              :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :with-credentials="true"
              accept="image/*" :headers="uploadHeaders">
              <el-button size="small">更换头像</el-button>
            </el-upload>

            <!-- <el-button v-if="userInfo.avatar" size="small" type="danger" style="margin-left: 8px;"
              @click="removeAvatar">
              删除头像
            </el-button> -->

            <div class="hint">支持 png/jpg/jpeg，大小不超过 2MB。</div>

            <el-button type="danger" plain class="logout-btn" @click="onLogoutClick">
              退出登录
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户数据
const userInfo = ref({})
const userInfoForm = ref({})

// 上传接口
const uploadUrl = '/user/uploadAvatar'
const uploadHeaders = {
  'token': localStorage.getItem('token')
}
// 获取用户信息
const getUser = async () => {
  try {
    const userId = localStorage.getItem("adminId")
    const res = await request.get(`/user/center/${userId}`)
    if (res.data.code === 200) {
      userInfo.value = res.data.data
      userInfoForm.value = { ...userInfo.value }
    } else {
      ElMessage.error(res.data.message || '获取用户信息失败')
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
}

// 保存基本资料
const saveProfile = async () => {
  const res = await request.put('/user/updateUser', {id: localStorage.getItem("adminId"), ...userInfoForm.value})
  if (res.data.code === 200) {
    ElMessage.success('更新成功')
    getUser()
  } else {
    ElMessage.error(res.data.message || '更新失败')
  }
}

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) return ElMessage.error('只能上传图片文件')
  if (!isLt2M) return ElMessage.error('图片不能大于2MB')
  return true
}

// 上传成功
const handleAvatarSuccess = async (res) => {
  if (res.code === 200) {
    ElMessage.success('头像更新成功')
    getUser()
  } else {
    ElMessage.error(res.message || '头像上传失败')
  }
}

// 删除头像
const removeAvatar = async () => {
  await ElMessageBox.confirm('确定删除头像？', '提示', { type: 'warning' })
  const res = await request.post('/user/removeAvatar')
  if (res.data.code === 200) {
    ElMessage.success('头像已删除')
    getUser()
  } else {
    ElMessage.error(res.data.message || '删除失败')
  }
}

// 退出登录
const onLogoutClick = () => {
  ElMessageBox.confirm(
    '确定要退出当前账号吗？',
    '退出登录',
    {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 可选：如果你的后端有 logout 接口
        await request.post('/user/logout')

        // 清除登录状态
        localStorage.clear()
        // localStorage.removeItem("token")
        // localStorage.removeItem("adminId")
        // localStorage.removeItem("type")

        ElMessage.success('退出成功')

        // 跳转登录页
        setTimeout(() => {
          router.replace('/login')
        }, 300)

      } catch (error) {
        ElMessage.error('退出失败')
      }
    })
    .catch(() => { /* 点击取消时不做处理 */ })
}

onMounted(() => getUser())
</script>

<style scoped>
.profile-page {
  padding: 12px;
}

.card-pro {
  border-radius: 14px;
  padding: 18px;
  background: rgba(255, 255, 255, 0.85);
  border: 1px solid #e9eef8;
  box-shadow: 0 8px 26px rgba(23, 46, 86, 0.04);
  height: 100%;
}

/* 左侧标题 */
.card-header .title {
  font-size: 18px;
  font-weight: 700;
}
.card-header .sub {
  font-size: 13px;
  color: #7f8a9a;
}

.pro-form {
  max-width: 720px;
  margin-top: 6px;
}

/* 右侧头像区域 */
.avatar-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}
.avatar-area {
  padding: 14px 0;
}
.big-avatar {
  border: 3px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 6px 20px rgba(34, 60, 80, 0.08);
  border-radius: 50%;
}
.avatar-name {
  margin-top: 12px;
  font-weight: 700;
  font-size: 18px;
}
.avatar-role {
  margin-top: 6px;
  font-size: 13px;
  color: #8892a0;
}

/* 上传区 */
.upload-area {
  text-align: center;
  width: 100%;
}
.hint {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}
.logout-btn {
  margin-top: 16px;
  width: 100%;
  border-radius: 10px;
  font-weight: 600;
  background: linear-gradient(135deg, #ff4f4f, #ff3a3a);
  color: white;
  border: none;
}
.logout-btn:hover {
  opacity: 0.92;
}
</style>
